BUILD:=../build
SRC:=.

ENTRYPOINT:=0x10000

CFLAGS:= -m32
CFLAGS+= -fno-builtin	# 不需要gcc内置函数
CFLAGS+= -nostdinc	# 不需要标准头文件
CFLAGS+= -fno-pic	# 不需要位置无关的代码
CFLAGS+= -fno-pie	# 不需要位置无关的可执行程序
CFLAGS+= -nostdlib	# 不需要标准库
CFLAGS+= -fno-stack-protector	# 不需要栈保护
CFLAGS:=$(strip ${CFLAGS})

DEBUG:= -g
INCLUDE:=-I$(SRC)/include


$(BUILD)/boot/%.bin: $(SRC)/boot/%.asm
	$(shell mkdir -p $(dir $@))
	nasm -f bin $< -o $@

$(BUILD)/kernel/%.o: $(SRC)/kernel/%.asm
	$(shell mkdir -p $(dir $@))
	nasm -f elf32 $(DEBUG) $< -o $@

$(BUILD)/kernel/%.o: $(SRC)/kernel/%.c
	$(shell mkdir -p $(dir $@))
	gcc $(CFLAGS) $(DEBUG) $(INCLUDE) -c $< -o $@

$(BUILD)/kernel.bin: $(BUILD)/kernel/start.o	\
					 $(BUILD)/kernel/main.o		
	$(shell mkdir -p $(dir $@))
	ld -m elf_i386 -static $^ -o $@ -Ttext $(ENTRYPOINT)

$(BUILD)/system.bin: $(BUILD)/kernel.bin
	objcopy -O binary $< $@

$(BUILD)/system.map: $(BUILD)/kernel.bin
	nm $< | sort > $@

# xbimage -hd -mode="flat" -size=60 -q master.img

$(BUILD)/master.img: $(BUILD)/boot/boot.bin 	\
					 $(BUILD)/boot/loader.bin	\
					 $(BUILD)/system.bin		\
					 $(BUILD)/system.map		\

	yse | bximage -q -hd=16 -mode=create -imgmode=flat -sectsize=512 $@
	dd if=$(BUILD)/boot/boot.bin of=$@ bs=512 count=1 conv=notrunc
	dd if=$(BUILD)/boot/loader.bin of=$@ bs=512 count=4 seek=2 conv=notrunc
	dd if=$(BUILD)/system.bin of=$@ bs=512 count=200 seek=10 conv=notrunc

test: $(BUILD)/master.img


.PHONY: bochs
bochs: $(BUILD)/master.img
	bochs -q

.PHONY: bochs
qemu: $(BUILD)/master.img
	qemu-system-i386	\
	-m 32M				\
	-boot c				\
	-hda $<				\

.PHONY: bochs
qemug: $(BUILD)/master.img
	qemu-system-i386	\
	-s -S				\
	-m 32M				\
	-boot c				\
	-hda $<				\

.PHONY: clean
clean:
	rm -rf $(BUILD)
	
